<template>
  <div>
    <div class="listTop">
      <div class="ui left aligned container">
        <div class="ui grid">
          <div class="ten wide column">
            <div class="ui segment">
              <h3 class="ui teal header" style="display:inline;">共享文档</h3>
              <p style="display:inline;float:right">共 {{ totalFiles }} 个文档</p>
              <el-divider></el-divider>
              <sui-card-group :items-per-row="1">
                <sui-card v-for="(fileList, index) in fileLists" :key="index" class="link">
                  <sui-item-content>
                    <div class="ui grid">
                      <div class="eleven wide column" @click="preview(index)">
                        <sui-item-header class="documentDescription">{{ fileList.realName
                        }}.{{ fileList.fileType }}</sui-item-header>
                        <sui-item-meta class="documentDescription" style="margin-top: 1rem;">
                          <span>文件描述：{{ fileList.description }}</span>
                        </sui-item-meta>
                      </div>
                      <div class="five wide column">
                        <sui-item-description style="float: right">
                          <i class="download icon"></i>
                          <el-button type="primary" size="small" @click="downloadFile(index)">下载文档</el-button>
                          <sui-item-meta style="margin-top: 1rem;">
                            <span>{{ fileList.code }}文件</span>
                          </sui-item-meta>
                        </sui-item-description>
                      </div>
                    </div>
                  </sui-item-content>
                  <sui-card-content extra style="padding:0.5rem 1rem;">
                    <span>
                      <i class="calendar alternate icon"></i>
                      {{ timestampToTime(fileList.uploadTime) }}
                    </span>
                    <span slot="right">
                      <el-avatar size="small" :src="img_url + fileList.profile" />
                      {{ fileList.nickname }}
                    </span>
                  </sui-card-content>
                </sui-card>
                <div class="loading" v-if="isLoading"><i class="el-icon-loading"></i>正在加载中...</div>
                <div class="loading" v-if="isEnding">已经到底了！</div>
              </sui-card-group>
            </div>
          </div>
          <div class="six wide column">
            <div class="ui segments searchBox">
              <div class="ui segment" style="margin-bottom:10px;!important">
                <h3 class="ui teal header">搜索文档</h3>
                <el-input placeholder="请输入内容" v-model="searchInput">
                  <el-select style="min-width: 8rem;" v-model="selectType" slot="prepend" placeholder="请选择">
                    <el-option label="文件名" value="1"></el-option>
                    <el-option label="文件类型" value="2"></el-option>
                  </el-select>
                  <el-button slot="append" icon="el-icon-search" @click="submitSearch"></el-button>
                </el-input>
              </div>
              <div class="ui segment searchRes">
                <el-empty v-if="searchFiles[0] == null" description="快来搜索文件吧！"></el-empty>
                <sui-card-group :items-per-row="1">
                  <sui-card v-for="(fileList, index) in searchFiles" :key="index" class="link">
                    <sui-item-content>
                      <div class="ui grid">
                        <div class="eleven wide column" @click="preview2(index)">
                          <sui-item-header class="documentDescription">{{ fileList.realName }}</sui-item-header>
                          <sui-item-meta class="documentDescription" style="margin-top: 1rem;">
                            <span>{{ fileList.description }}</span>
                          </sui-item-meta>
                        </div>
                        <div class="five wide column">
                          <sui-item-description style="float: right">
                            <i class="download icon"></i>
                            <el-button type="text" @click="searchDownloadFile(index)">下载文档</el-button>
                            <sui-item-meta style="margin-top: 1rem;">
                              <span>{{ fileList.code }}文件</span>
                            </sui-item-meta>
                          </sui-item-description>
                        </div>
                      </div>
                    </sui-item-content>
                    <sui-card-content extra style="padding:0.5rem 1rem;">
                      <span>
                        <i class="calendar alternate icon"></i>
                        {{ timestampToTime(fileList.uploadTime) }}
                      </span>
                      <span slot="right">
                        <el-avatar size="small" :src="img_url + fileList.profile" />
                        {{ fileList.nickname }}
                      </span>
                    </sui-card-content>
                  </sui-card>
                </sui-card-group>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { view } from '../../utils/func';
export default {
  data() {
    return {
      fileLists: {},       //接收文件数组  
      img_url: 'http://1.14.48.193:8888/img/',
      fileContent: null,
      identify: JSON.parse(sessionStorage.getItem('userInfo')).role,
      downloadURL: '',                               //下载地址
      totalFiles:0,                                //文件总数
      searchInput: '',                                //查询内容
      selectType: '1',                                  //选择查询方式 
      searchFiles: {},          //搜索文件数组
      isSearch: false,           //判断是否是搜索的内容
      page: 0,                     //当前为第几页
      isEnding: false,             //判断是否没有数据了
      isLoading:false,               //判断是否在加载
    }
  },
  methods: {
    submitSearch() {
      if (this.selectType == '1') {
        this.$https({
          method: 'get',
          url: '/user/fileListByName',
          params: {
            fileName: this.searchInput
          }
        }).then(res => {
          console.log(res);
          if (res.data.code == 200) {
            if (res.data.data == false) this.$message.info("没有找到相关文件！");
            else this.searchFiles = res.data.data;
          } else
            this.$message.info(res.data.data);
        })
      } else {
        this.$https({
          method: 'get',
          url: '/user/fileListByType',
          params: {
            fileType: this.searchInput
          }
        }).then(res => {
          if (res.data.code == 200)
            this.searchFiles = res.data.data;
          else
            this.$message.success(res.data.data);
        })
      }
    },
    preview(index) {
      view(this.fileLists[index]);
    },
    preview2(index) {
      view(this.searchFiles[index]);
    },
    downloadFile(index) {
      var documentId = this.fileLists[index].id;     //获取文件id
      var documentType = this.fileLists[index].code  //获取文件是否加密
      if (this.identify == 'admin')
        this.downloadURL = "/admin/download";
      else
        this.downloadURL = "/user/download";

      if (documentType == '加密' && this.identify != 'admin') {
        this.$prompt('请输入密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[a-zA-Z0-9]{4,6}/,
          inputErrorMessage: '密码格式不正确'
        }).then(({ value }) => {
          this.$https({
            method: 'get',
            url: this.downloadURL,
            params: {
              fileId: documentId,
              code: value
            },
            header: {
              headers: { 'Content-Type': 'application/x-download' }
            },
            responseType: 'blob'
          }).then((res) => {
            const fileType = res.headers['content-type'];
            const fileName = decodeURI(res.headers['filename'])
            const blob = new Blob([res.data], { type: fileType });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.target = '_blank';
            a.style.display = 'none';
            a.download = fileName + '.' + fileType.substring(fileType.lastIndexOf('/') + 1);
            a.click();
            window.URL.revokeObjectURL(url);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消下载'
          });
        });
      } else {
        this.$https({
          method: 'get',
          url: this.downloadURL,
          params: {
            fileId: documentId,
            code: this.code
          },
          header: {
            headers: { 'Content-Type': 'application/x-download' }
          },
          responseType: 'blob'
        }).then((res) => {
          console.log(res);
          const fileType = res.headers['content-type'];
          const fileName = decodeURI(res.headers['filename'])
          const blob = new Blob([res.data], { type: fileType });
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = fileName + '.' + fileType.substring(fileType.lastIndexOf('/') + 1);
          a.click();
          window.URL.revokeObjectURL(url);
        })
      }
    },
    searchDownloadFile(index) {
      var documentId = this.searchFiles[index].id;     //获取文件id
      var documentType = this.searchFiles[index].code  //获取文件是否加密
      if (this.identify == 'admin')
        this.downloadURL = "/admin/download";
      else
        this.downloadURL = "/user/download";

      if (documentType == '加密' && this.identify != 'admin') {
        this.$prompt('请输入密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[a-zA-Z0-9]{4,6}/,
          inputErrorMessage: '密码格式不正确'
        }).then(({ value }) => {
          this.$https({
            method: 'get',
            url: this.downloadURL,
            params: {
              fileId: documentId,
              code: value
            },
            header: {
              headers: { 'Content-Type': 'application/x-download' }
            },
            responseType: 'blob'
          }).then((res) => {
            const fileType = res.headers['content-type'];
            const fileName = decodeURI(res.headers['filename'])
            const blob = new Blob([res.data], { type: fileType });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.target = '_blank';
            a.style.display = 'none';
            a.download = fileName + '.' + fileType.substring(fileType.lastIndexOf('/') + 1);
            a.click();
            window.URL.revokeObjectURL(url);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消下载'
          });
        });
      } else {
        this.$https({
          method: 'get',
          url: this.downloadURL,
          params: {
            fileId: documentId,
            code: this.code
          },
          header: {
            headers: { 'Content-Type': 'application/x-download' }
          },
          responseType: 'blob'
        }).then((res) => {
          console.log(res);
          const fileType = res.headers['content-type'];
          const fileName = decodeURI(res.headers['filename'])
          const blob = new Blob([res.data], { type: fileType });
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = fileName + '.' + fileType.substring(fileType.lastIndexOf('/') + 1);
          a.click();
          window.URL.revokeObjectURL(url);
        })
      }
    },
    getDocumentList() {
      let size = 5;
      this.$https({
        method: 'get',
        url: '/user/fileListByPage',
        params: {
          current: this.page + 1,
          size: size
        }
      }).then((res) => {
        if (res.data.code == 200) {
          //文件总数及每一页文件长度
          this.totalFiles = res.data.data.total;
          let length = res.data.data.records.length;
          //判断是否到底了
          if (length == 0) { this.isEnding = true; this.isLoading = false; return; }
          if (this.fileLists == null || this.fileLists[0]==null) { var arr = [];}
          else { var arr = this.fileLists; }
          arr.length = this.page * size + length;
          let begin = this.page * size;
          for (let i = 0; i < length; i++) {
            //直接更改数组 不能被监听  需要使用set方法
            // arr[begin + i] = res.data.data.records[i];
            this.$set(arr, begin + i, res.data.data.records[i]);
          }
          this.fileLists = arr;
          this.isLoading = false;
          // this.$forceUpdate();
        } else
          this.$message.info(res.data.message);
      })
    },
    listenBottom() {
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部的高度  
      var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight; //当前页面的总高度  
      var clientHeight = document.documentElement.clientHeight || document.body.clientHeight; //当前可视的页面高度  
      if (scrollTop + clientHeight >= scrollHeight-1) { //距离顶部+当前高度 >=文档总高度 即代表滑动到底部   
        //滚动条到达底部  
        //将页数加1
        if (!this.isEnding) { this.isLoading = true; }
        this.page = this.page + 1;
        setTimeout(this.getDocumentList, 2000);
      } else if (scrollTop <= 0) {
        //滚动条到达顶部  
        //滚动条距离顶部的高度小于等于0 TODO  
      }
    },
    timestampToTime(time) {
      //时间戳转换
      // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var date = new Date(time);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      let d = date.getDate();
      let h = date.getHours();
      let m = date.getMinutes();
      let s = date.getSeconds();
      MM = MM < 10 ? "0" + MM : MM;
      d = d < 10 ? "0" + d : d;
      h = h < 10 ? "0" + h : h;
      m = m < 10 ? "0" + m : m;
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    },
    stikySearch() {
      let nav = document.querySelector('.searchBox');
      if (window.pageYOffset > nav.offsetTop + 150) {
        nav.style.position = 'fixed'
        nav.style.top = '0px'
        nav.style.width = '400px'
        nav
      } else {
        nav.style.position = 'static'
      }
    }
  },
  created() {

    setInterval(window.addEventListener('scroll', this.listenBottom), 1000);
    window.addEventListener('scroll', this.stikySearch);
  },
  mounted() {
    this.getDocumentList(1);
  },
  destroyed() {
    window.removeEventListener('scroll', this.stikySearch);
  }
}
</script>

<style scoped>
.searchBox {
  position: sticky;
  top: 0;
}

.searchRes {
  height: 40rem;
  overflow-y: scroll;
}

.listTop {
  padding-top: 5em !important;
  padding-bottom: 5em !important;
}

.loading{
  margin: 1rem auto;
}

.documentDescription {
  word-break: keep-all;
  /* 不换行 */
  white-space: nowrap;
  /* 不换行 */
  overflow: hidden;
  /* 内容超出宽度时隐藏超出部分的内容 */
  text-overflow: ellipsis;
  /* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用*/
}
</style>